package com.jml.jdbc.annotationdemo;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan(basePackages = "com.jml.jdbc.annotationdemo")
@EnableTransactionManagement
public class JdbcConfigBean {

    @Bean(destroyMethod = "close")
    public DataSource dataSource(){
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("1234");
        return basicDataSource;
    }

    @DependsOn("dataSource")
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    /**
     *
     *@EnableTransactionManagement注解事务要使用到这个事务管理器，只有spring会用到，如果是springboot就不用，jar包帮我们自动加入了。这个会在拦截器要用到，去进行getBean获取
     */
    @DependsOn("dataSource")
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    // 在拦截器器中获取事务管理器，管理器的的方法开启事务   都会新建一个DataSourceTransactionObject
}
